﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ContactSMS.Client.Common;
using ContactSMS.Client.Models;
using ContactSMS.Client.Views;
using ContactSMS.Client.Views.Controls;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Compatibility;
using System.Collections.ObjectModel;
using ContactSMS.Client.Response;
using ContactSMS.Client.Service;
using Newtonsoft.Json;
using System.Linq;

namespace ContactSMS.Client.ViewModels
{
    public partial class ContactViewModel : ObservableObject
    {
        //会生成一个名为 ContactGroups 的属性
        //当 ContactGroups 的值更改时，界面会自动更新。
        [ObservableProperty]
        public ObservableCollection<ContactGroupModel> contactGroups = new ObservableCollection<ContactGroupModel>();

        [ObservableProperty]
        public ObservableCollection<ContactGroupModelNew> contactGroupModelNew = new ObservableCollection<ContactGroupModelNew>();

        //public ObservableCollection<string> Letters { get; set; }

        public ObservableCollection<LettersModel> Letters { get; set; }

        [ObservableProperty]
        private string selectedItem;

        [ObservableProperty]
        private string selectedLetters;

        private readonly ContactService contactService;

        [ObservableProperty]
        private List<ContactModel> contacts;

        public event EventHandler<ContactGroupModel> ScrollRequested;
        private void OnScrollRequested(ContactGroupModel g)
        {
            ScrollRequested?.Invoke(this, g);
        }

        public ContactViewModel(ContactService contactService)
        {
            //Letters = new ObservableCollection<string>
            //{
            //    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
            //    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
            //};
            LoadLetters();
            //LoadContacts();
            this.contactService = contactService;
        }

        [RelayCommand]
        public async Task LoadContactss()
        {
            try
            {
                var result = await contactService.GetContactsAsync(1, 1000);
                if (result != null && result.Success)
                {
                    // 按照首字母进行分组
                    var groupedContacts = result.Data.List
                        .Where(contact => !string.IsNullOrEmpty(contact.Initial)) // 确保 Initial 不为空
                        .GroupBy(contact => contact.Initial.ToUpper()) // 按照首字母分组
                        .OrderBy(group => group.Key) // 按字母顺序排序
                        .Select(group => new ContactGroupModelNew(group.Key, group.ToList())) // 将每个分组转换为 ContactGroup 对象
                        .ToList(); // 转换为列表// 转换为列表

                    ContactGroupModelNew = new ObservableCollection<ContactGroupModelNew>(groupedContacts);
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Error", result?.Message ?? "Failed to load contacts", "OK");
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
        }

        void LoadLetters()
        {
            Letters = new ObservableCollection<LettersModel>
            {
                new LettersModel
                {
                    Name="A",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="B",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="C",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="D",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="E",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="F",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="G",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="H",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="I",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="J",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="K",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="L",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="M",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="N",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="O",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="P",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="Q",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="R",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="S",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="T",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="U",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="V",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="W",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="X",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="Y",
                    Color=Colors.Gray
                },
                new LettersModel
                {
                    Name="Z",
                    Color=Colors.Gray
                }
            };
        }

        void LoadContacts()
        {
            /*            ContactGroups.Add(new ContactGroupModel("A", new ObservableCollection<ContactModel>
                        {
                            new ContactModel{ Id=1,Name="A",Avatar="/contact/avatar.png"},
                            new ContactModel{ Id=2,Name="A1",Avatar="/contact/avatar.png"},
                        }));*/
            var contacts = new ObservableCollection<ContactModel> { };
            //var word = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            var word = LetterLists.GetLetters();
            for (int i = 0; i < 26; i++)
            {
                contacts.Add(new ContactModel
                {
                    Id = i + 1,
                    Name = word[i],
                    Avatar = "/contact/avatar.png"
                });
            }
            for (int i = 0; i < 26; i++)
            {
                contacts.Add(new ContactModel
                {
                    Id = i + 1,
                    Name = word[i],
                    Avatar = "/contact/avatar.png"
                });
            }

            var grouped = contacts
                .GroupBy(c => c.Name[0].ToString().ToUpper())
                .Select(g => new ContactGroupModel(g.Key, g))
                .OrderBy(g => g.Name);

            foreach (var group in grouped)
            {
                ContactGroups.Add(group);
            }
        }

        [RelayCommand]
        public void HuaDong(object obj)
        {
            SelectedItem = obj.ToString();
            SelectedLetters = obj.ToString();
            var group = ContactGroups.FirstOrDefault(g => g.Name == obj.ToString());
            //var letters = Letters.FirstOrDefault(g => g == obj.ToString());
            if (group != null)
            {
                var index = ContactGroups.IndexOf(group);
                if (index >= 0)
                {
                    OnScrollRequested(group);
                }
            }
            /*var letters = Letters.FirstOrDefault(g => g.Name == obj.ToString());
            if (letters != null)
            {
                letters.Color = Colors.Green;
            }
            Console.WriteLine(Letters);*/
            foreach (var letter in Letters)
            {
                letter.Color = letter.Name == obj.ToString() ? Colors.Green : Colors.Gray;
            }
        }

        [RelayCommand]
        public async Task LongPress(ContactModel contact)
        {
            bool isDelete = await Application.Current.MainPage.DisplayAlert("Long Press", $"Do you want to delete {contact.Name}?", "Yes", "No");
            if (isDelete)
            {
                //Contacts.Remove(contact);
            }
        }

        [RelayCommand]
        public async Task CommonSearch()
        {
            await Shell.Current.GoToAsync(nameof(CommonSearchPage));
        }

        [RelayCommand]
        public async Task CommonAddContact()
        {
            await Shell.Current.GoToAsync(nameof(AddContactPage));
        }

        [RelayCommand]
        public async Task NavigateToDetail(long ContactId)
        {
            //await Shell.Current.GoToAsync(nameof(ContactDetailPage));
            await Shell.Current.GoToAsync($"{nameof(ContactDetailPage)}?Id={ContactId}");
        }

        [RelayCommand]
        public void CommonAddMenu(object obj)
        {
            var popupMenu = obj as PopupMenu;
            popupMenu.IsVisible = true;
            RelativeLayout.SetXConstraint(popupMenu,
                Constraint.RelativeToParent((parent) => parent.Width - popupMenu.Width));
            RelativeLayout.SetYConstraint(popupMenu,
                Constraint.Constant(0));
        }
    }
}
